package com.blue.base.xxljob;

import com.xxl.job.core.executor.impl.XxlJobSpringExecutor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.commons.util.InetUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;

import java.util.Optional;

/**
 * The type XxlJobAutoConfiguration.
 *
 * @author liulei
 * @version 1.0
 */
@Slf4j
@Configuration
public class XxlJobAutoConfiguration {

    public XxlJobAutoConfiguration() {
        log.info("==========初始化XxlJob模块==========");
    }

    @Value("${xxl.job.admin.addresses}")
    private String adminAddresses;

    @Value("${xxl.job.accessToken}")
    private String accessToken;

    @Value("${xxl.job.executor.appname}")
    private String appname;

    @Value("${xxl.job.executor.port}")
    private int port;

    @Value("${xxl.job.executor.logpath}")
    private String logPath;

    @Value("${xxl.job.executor.logretentiondays}")
    private int logRetentionDays;

    /**
     * 注册xxl-job分布式定时任务执行器信息
     */
    @Bean
    public XxlJobSpringExecutor xxlJobExecutor(Environment environment, InetUtils inetUtils) {
        log.info(">>>>>>>>>>> sys xxl-job com.blue.base.web.config init.");
        XxlJobSpringExecutor executor = new XxlJobSpringExecutor();
        String fixAppName = environment.getProperty("spring.application.name");
        executor.setAdminAddresses(adminAddresses);
        executor.setAppname(Optional.ofNullable(appname).orElse(fixAppName));
        String ipAddress = inetUtils.findFirstNonLoopbackHostInfo().getIpAddress();
        executor.setIp(ipAddress);
        executor.setPort(port);
        executor.setAccessToken(accessToken);
        executor.setLogPath(logPath);
        executor.setLogRetentionDays(logRetentionDays);
        return executor;
    }
}
